import 'dart:isolate';

import 'package:flutter/cupertino.dart';
import 'package:flutter_test1/helper/web3_utils.dart';
import 'package:flutter_test1/model/account_model.dart';

class AccountGenerator {
  late Isolate _isolate;
  late SendPort _sendPort;
  bool _isRunning = false;
  ReceivePort? _receivePort; // 用于确保只有一个监听器

  /// 启动生成器
  Future<void> startGenerating(Function(AccountModel) onAccountGenerated) async {
    if (_isRunning) return; // 防止重复启动
    _isRunning = true;

    // 如果已有 ReceivePort，直接使用，否则创建
    _receivePort ??= ReceivePort();

    // 启动 Isolate
    _isolate = await Isolate.spawn(_generateLoop, _receivePort!.sendPort);

    // 接收来自 Isolate 的初始发送端口
    _sendPort = _receivePort!.sendPort;

    // 监听来自子线程的消息
    _receivePort!.listen((message) {
      debugPrint('_receivePort listen 的 msg: $message ');
      if (message is Map<String, dynamic>) {
        // onAccountGenerated(message); // 回调主线程处理
      }
      if (message is AccountModel) {
        onAccountGenerated(message); // 回调主线程处理
      }
    });

    // 开始生成任务
    _sendPort.send({'command': 'start'});
  }

  /// 停止生成器
  void stopGenerating() {
    if (!_isRunning) return;
    _isRunning = false;

    // 发送停止信号
    _sendPort.send({'command': 'stop'});

    // 停止 Isolate
    _isolate.kill(priority: Isolate.immediate);
    _receivePort?.close(); // 关闭接收端口
    _receivePort = null;
  }

  /// 生成循环的后台任务
  static void _generateLoop(SendPort sendPort) {
    sendPort.send("开始生成账号");

    while (true) {
      final account = generateEthereumAccount();
      if (account != null) {
        sendPort.send(account); // 返回生成的账号
      }
      // await Future.delayed(Duration(milliseconds: 500)); // 控制生成频率
    }

  }
}

AccountModel? generateEthereumAccount() {
  var result = Web3Utils.generateEthereumAccount();
  // debugPrint('产生的account: $result');
  var ethAddress = result['address'];
  String tronAddress = Web3Utils.ethereumToTron(ethAddress);
  final tail = ethAddress.substring(2); // 去掉 0x 前缀
  final tail2 = tronAddress.substring(2);
  int ethTail = 0;
  int tronTail = 0;

  final regex = RegExp(r'(.)\1{2,}$');
  if (regex.hasMatch(tail)) {
    final match = regex.firstMatch(ethAddress);
    if (match != null) {
      String fullMatch = match.group(0)!;
      ethTail = fullMatch.length;
    }

    return AccountModel(
        ethereumAddress: result['address'],
        tronAddress: Web3Utils.ethereumToTron(ethAddress),
        bitcoinAddress: '',
        privateKey: result['privateKey'],
        publicKey: result['publicKey'],
        ethTail: ethTail,
        tronTail: 0
    );

  } else if (regex.hasMatch(tail2)) {
    final match = regex.firstMatch(tronAddress);
    if (match != null) {
      String fullMatch = match.group(0)!;
      tronTail = fullMatch.length;
    }

    return AccountModel(
        ethereumAddress: result['address'],
        tronAddress: Web3Utils.ethereumToTron(ethAddress),
        bitcoinAddress: '',
        privateKey: result['privateKey'],
        publicKey: result['publicKey'],
        ethTail: 0,
        tronTail: tronTail
    );
  }

  // debugPrint('结果不符合');
  return null;
}


